#include "ws_protocol_service.h"
#include "utils_log.h"
#include "ws_connection_manager.h"

namespace El {
namespace Restful {

WebSocketProtocolService &WebSocketProtocolService::GetInstance()
{
    static WebSocketProtocolService instance;
    return instance;
}

WebSocketProtocolService::~WebSocketProtocolService()
{
    Stop();
}

bool WebSocketProtocolService::Start()
{
    if (running_) {
        return true;
    }
    // 初始化事件队列
    event_queue_ = std::make_unique<El::Utils::BlockingQueue<std::shared_ptr<El::WebServer::WebSocketEvent>>>(
        "WebSocketEventQueue", 100);

    // 启动处理线程
    running_ = true;
    process_thread_ = std::make_unique<std::thread>(&WebSocketProtocolService::ProcessWebSocketEvents, this);

    // 注册WebSocket处理
    auto &http_server = El::WebServer::IHttpServer::GetInstance();
    if (!http_server.RegisterWebSocketHandler(
            "^/v1/protocol$",
            [this](std::shared_ptr<El::WebServer::WebSocketEvent> &event) { HandleWebSocketEvent(event); })) {
        EL_ERROR("Failed to register WebSocket handler");
        Stop();
        return false;
    }
    http_server.AddAuthExemptUrl("^/v1/protocol$");

    return true;
}

void WebSocketProtocolService::Stop()
{
    if (!running_) {
        return;
    }

    // 停止处理线程
    running_ = false;

    // 停止队列
    if (event_queue_) {
        event_queue_->SetActive(false);
    }

    // 等待线程结束
    if (process_thread_ && process_thread_->joinable()) {
        process_thread_->join();
        process_thread_ = nullptr;
    }

    // 清理资源
    event_queue_ = nullptr;
}

void WebSocketProtocolService::HandleWebSocketEvent(std::shared_ptr<El::WebServer::WebSocketEvent> &event)
{
    // 将事件推送到队列
    if (event_queue_ && !event_queue_->Push(event)) {
        EL_ERROR("Failed to push WebSocketEvent to queue: queue is full or inactive");
    }
}

void WebSocketProtocolService::ProcessWebSocketEvents()
{
    EL_INFO("WebSocket event processing thread started");

    while (running_) {
        // 从队列获取事件，设置超时为100ms，定期检查running_状态
        auto event = event_queue_->Pop(100);
        if (event == nullptr) {
            continue;
        }

        nlohmann::json json_event = nlohmann::json::parse(event->message, nullptr, false);
        if (!json_event.is_discarded()) {
            // 仅打印前100字节，避免日志过长
            constexpr size_t kMaxLogBytes = 100;
            std::string dumped = json_event.dump(); // 使用紧凑格式
            if (dumped.size() > kMaxLogBytes) {
                EL_DEBUG(
                    "Processing WebSocketEvent connection_id: {} from queue (truncated {}>{}): {}...", 
                    event->connection_id, dumped.size(), kMaxLogBytes, dumped.substr(0, kMaxLogBytes));
            } else {
                EL_DEBUG("Processing WebSocketEvent connection_id: {} from queue: {}", event->connection_id, dumped);
            }
        }

        try {
            // 使用WebSocketEventProcessor处理事件
            auto &processor = WebSocketConnectionManager::GetInstance();
            std::string response = processor.ProcessEvent(event);

            // 如果有响应消息，则发送回客户端
            if (!response.empty()) {
                auto &http_server = El::WebServer::IHttpServer::GetInstance();
                if (!http_server.SendWebSocketTextMessage(event->connection, response)) {
                    EL_ERROR("Failed to send response to client");
                } else {
                    nlohmann::json json_response = nlohmann::json::parse(response);
                    EL_DEBUG("Sent connection_id: {} response to client: {} ", event->connection_id,
                              json_response.dump(4));
                }
            }
        } catch (const std::exception &e) {
            EL_ERROR("Exception while processing WebSocket event: {}", e.what());
        }
    }

    EL_INFO("WebSocket event processing thread stopped");
}

} // namespace Restful
} // namespace El